package chrome;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class c {

	private static int fnName = 1;
	private final static String ROOT = "structured/";
	private final static String ROOT_FUNCTION_START = "var _EsdDynamicTransformationFunction = function($){";
	private final static String ROOT_FUNCTION_END = "};";
	private static String[] models = new String[11];
	static {
		// 公用的
		models[0] = "main.js";// 引入名字控件
		models[1] = "name_space.js";// 入口,声明
		models[2] = "area_nav.js";// 区域导航公有的+红边框
		// site
		models[3] = "a.js";// 控件处理，a
		models[4] = "img.js";// 图片处理，img
		models[5] = "main_header.js";// 网站头部
		models[6] = "main_nav.js";// 主导航
		models[7] = "slide.js";// 首页的轮播
		models[8] = "html";// 这是一个文件夹
		models[9] = "main_footer.js";// 底部
		models[10] = "nav_block_selector.js";// 各页面不同的的区块跳转

	}

	public static void runtimeCommand(String s) throws Exception {

		//Process process = Runtime.getRuntime().exec("cmd.exe /c dir");
		Process process = Runtime.getRuntime().exec(s);
		int status = process.waitFor();

		System.out.println(status);
		InputStream in = process.getInputStream();

		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line = br.readLine();
		while (line != null) {
			System.out.println(line);
			line = br.readLine();
		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 会在对应目录的online下生成一个整体的JS脚本
		// compile("gdj");
		look("dfz", false);// 生成查看效果一次完成
	}

	public static void look(String site, Boolean debug) {
		StringBuffer sb = c.compile(site, debug);
		System.out.println(sb);
		WebDriver wd = new ChromeDriver();
		wd.get("http://" + site + ".jl.gov.cn/");
		JavascriptExecutor js = (JavascriptExecutor) wd;
		js.executeScript(sb.toString());
	}

	public static StringBuffer compile(String site, Boolean debug) {
		StringBuffer sbb = new StringBuffer();
		sbb.append(ROOT_FUNCTION_START).append("\n");// 方法开启
		append(sbb, 1, debug);
		for (int i = 3; i < models.length; i++) {
			if (models[i].equals("html")) {
				String s = ROOT + site + "/dev/html";
				ArrayList<File> lf = getListFiles(s);
				for (Iterator iterator = lf.iterator(); iterator.hasNext();) {
					File file = (File) iterator.next();
					StringBuffer r = readFileByLines(file.getAbsolutePath(), debug);
					sbb.append(r);
				}
				continue;
			}
			String f = ROOT + site + "/dev/" + models[i];
			// System.out.println(f);
			StringBuffer r = readFileByLines(f, debug);
			sbb.append(r);
		}
		append(sbb, 2, debug);
		sbb.append(ROOT_FUNCTION_END).append("\n");// 方法结束
		append(sbb, 0, debug);// 添加程序入口
		// System.out.println(sbb.toString());
		String online = ROOT + site + "/online/";
		File fi = new File(online);
		if (fi.exists() == false) {
			fi.mkdirs();
		}
		String out = ROOT + site + "/online/esd_wza_Script_" + site + ".js";
		writerJs(sbb, out);
		String min = ROOT + site + "/online/esd_wza_Script_" + site + "_min.js";
		String cmd = "java -jar closure-compiler-v20200224.jar --js " + out + " --js_output_file " + min;
		try {
			runtimeCommand(cmd);
			//Process p = Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (debug) {// 调试模式直接返回
			return sbb;
		}
		sbb = readFileByLines(min);
		return sbb;
	}

	public static void append(StringBuffer sbb, int i, Boolean debug) {
		String dir = ROOT + "a_esd_public/" + models[i];
		StringBuffer r = readFileByLines(dir, debug);
		sbb.append(r);
		// System.out.println("加载：" + dir + "[true]");
	}

	public static void writerJs(StringBuffer sb, String targetPath) {
		// 写入文件
		// String targetPath = ROOT + site + "//";// 目标文件路径
		File f = new File(targetPath);// 新建文件
		if (f.exists()) {
			f.delete();
		}
		f = new File(targetPath);// 新建文件
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(f));
			bw.write(sb.toString());
			bw.flush();
			bw.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	public static StringBuffer readFileByLines(String fileName, Boolean debug) {

		File file = new File(fileName);

		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();

		try {
			// System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				if (debug) {
					sb.append(tempString).append("\n");
				} else {
					String s = tempString.trim();
					boolean log = s.startsWith("console.log");
					if (log) {
						continue;
					}
					sb.append(s).append("\n");
				}

			}
			reader.close();

			// for (Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
			// it.hasNext();) {
			// Entry<String,String> type = (Entry) it.next();
			// sb = new StringBuffer(sb.toString().replaceAll(type.getKey(),
			// type.getValue()));
			// }

			return sb;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb;
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	public static StringBuffer readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
			String tempString = null;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				sb.append(tempString).append("\n");

			}
			reader.close();
			return sb;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb;
	}

	public static Map<String, String> map = new HashMap<String, String>();

	public static String funPro(String fn) {
		if (fn.startsWith("_E.")) {

			int d = fn.indexOf("=");
			if (d != -1) {
				String bl = fn.substring(0, d);
				// System.out.println(bl);
				map.put(bl.trim(), "_E.a" + fnName++);

			}

		}

		return fn;
	}

	public static String varPro(String fn) {
		if (fn.startsWith("var ")) {

			System.out.println(fn);
			// int d = fn.indexOf("=");
			// if (d != -1) {
			// String bl = fn.substring(0, d);
			// System.out.println(bl);
			// map.put(bl.trim(), "_E.a"+fnName++);
			//
			//
			// }

		}

		return fn;
	}

	public static String linezs(String str) {
		str = str.trim();
		int t = str.indexOf("//");
		if (t == -1) {
			return str;
		}
		// String[] split = str.split("//");
		// for (int i = 0; i < split.length; i++) {
		// System.out.println("["+i+"]:"+split[i]);
		// }
		// 双引号
		int xy_start = str.indexOf("\"", t);
		if (xy_start != -1) {
			int xy_end = str.lastIndexOf("\"", t);
			if (xy_end != -1) {
				return str;
			}
		}
		// 单引号
		int dy_start = str.indexOf("'", t);
		if (dy_start != -1) {
			int dy_end = str.lastIndexOf("'", t);
			if (dy_end != -1) {
				return str;
			}
		}
		// System.out.println(str);
		str = str.substring(0, t);
		// System.out.println(str);

		return str.trim();
	}

	/***
	 * 获取指定目录下的所有的文件（不包括文件夹），采用了递归
	 * 
	 * @param obj
	 * @return
	 */
	public static ArrayList<File> getListFiles(Object obj) {
		File directory = null;
		if (obj instanceof File) {
			directory = (File) obj;
		} else {
			directory = new File(obj.toString());
		}
		ArrayList<File> files = new ArrayList<File>();
		if (directory.isFile()) {
			files.add(directory);
			return files;
		} else if (directory.isDirectory()) {
			File[] fileArr = directory.listFiles();
			for (int i = 0; i < fileArr.length; i++) {
				File fileOne = fileArr[i];
				files.addAll(getListFiles(fileOne));
			}
		}
		return files;
	}
}
